package com.google.code.shardbatis.sharding.key;

import org.apache.commons.lang3.StringUtils;

public class GhostKeyParser {
    private GhostKeyParser() {

    }

    public static long getDatacenterId(long input) {
        String binaryString = Long.toBinaryString(input);
        int leftPadSize = 64 - binaryString.length();
        if (leftPadSize > 0) {
            //不满足64位高位补0
            binaryString = StringUtils.leftPad(binaryString, 64, "0");
        }

        //前38位表示时间[0,42)
        long timeDiff = Long.parseLong(binaryString.substring(0, 42), 2);
        if (timeDiff + GhostKeyGenerator.UNIX_BASE_DATE < GhostKeyGenerator.EPOCH) {
            return 0L;
        }

        //5计算DatacenterId[42,47)
        //5计算WorkerId[47,52)
        //12毫秒内自增位[52,64）
        return Long.parseLong(binaryString.substring(42, 47), 2);
    }
}
